package team.wuyou.util.httpUtil;

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @Description 传入参数，发起http请求，返回值为String类型的响应信息
 * @Date 2024/1/9 20:23
 * @Wang
 **/
public class HttpUtil {
    public static String request(String url, Map map) throws IOException {
        //可关闭的 Http 响应
        CloseableHttpResponse response = null;
        String result = null;
        try {
            //创建一个默认客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //准备一个url链接
            URIBuilder urlBuilder = new URIBuilder(url);
            Set<Map.Entry> set = map.entrySet();

            for (Map.Entry entry : set) {
                //为链接设置参数
                urlBuilder.setParameter(entry.getKey() + "", entry.getValue() + "");
            }
            //获取一个get请求
            HttpPost httppost = new HttpPost(urlBuilder.build());
            //客户端执行post请求，并获取响应
            response = httpClient.execute(httppost);
            result = null;
            //获取状态
            StatusLine statusLine = response.getStatusLine();
            System.out.println(statusLine);
            //Http实体          响应      获取实体
            HttpEntity entity = response.getEntity();
            //输出响应实体
            result = EntityUtils.toString(entity);
            System.out.println("响应的内容为：" + result);
        } finally {
            //关闭响应
            response.close();
            return result;
        }
    }
}
